<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-permission="['category:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate({id:0,name:'根节点'})">添加</el-button>
    </div>
    <el-table :data="categories" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" style="width: 100%;margin-bottom: 20px;" row-key="id" border>
      <el-table-column prop="name" label="名称" width="180"/>
      <el-table-column prop="seq" label="排序" sortable width="180"/>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <el-image :src="scope.row.url+'_120_60'"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button v-permission="['category:add']" type="text" size="mini" @click="handleCreate(scope.row)">添加</el-button>
          <el-button v-permission="['category:detail']" v-if="scope.row.id!=0" type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['category:delete']" v-if="scope.row.id!=0" type="text" size="mini" @click="() => remove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :close-on-click-modal="false" :title="isAdd?'新增':'编辑'" :visible.sync="dialogFormVisible" @close="destroyDialog">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="right" label-width="100px">
        <el-form-item label="类目ID" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item v-if="isAdd" label="父类ID" prop="parentId" hidden>
          <el-input v-model="dataForm.parentId" />
        </el-form-item>
        <el-form-item v-if="isAdd" label="父类" prop="parentName">{{ dataForm.parentName }}</el-form-item>
        <el-form-item label="类目名称" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-input v-model.number="dataForm.seq" />
        </el-form-item>
        <el-form-item label="类目图片" prop="pic">
          <uploader :file-list.sync="fileList" @success="uploadCoverSuccess" @remove="removeCoverSuccess"/>
          <div class="margin-top-20"/>
          <el-alert :closable="false" title="提示:" type="success">
            <template slot="title">
              <div>1.产品类目建议最多两级目录</div>
              <div>2.产品大类图片尺寸建议310px ✖ 120px 子类图片建议52px ✖ 52px</div>
            </template>
          </el-alert>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-permission="['category:add']" v-if="isAdd" type="primary" @click="save">确定</el-button>
        <el-button v-permission="['category:edit']" v-else type="primary" @click="edit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { CategoryService } from '@/api/ProductService'
import Uploader from '@/components/Uploader'
import Notify from '@/utils/notify'

export default {
  name: 'Category',
  components: { Uploader },
  data() {
    return {
      categories: [], fileList: [],
      dataForm: { id: 0, name: undefined, parentId: 0, parentName: undefined, pic: undefined, seq: 0 },
      dialogFormVisible: false,
      isAdd: true,
      rules: {
        name: [{ required: true, message: '名称不能为空!', trigger: 'blur' }],
        seq: [{ required: true, message: '排序不能为空', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    initList() {
      this.categories = []
      CategoryService.loadCategoryTree().then(result => {
        const root = { id: 0, name: '根节点' }
        root.children = result
        this.categories = result
      })
    },
    resetForm() {
      this.dataForm = { id: 0, name: undefined, parentId: 0, pic: undefined }
    },
    remove(data) {
      this.$confirm('您确认要删除 ' + data.name + ' 这个产品类目吗?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        CategoryService.deleteCategory(data.id).then(() => {
          this.initList()
          Notify.success(this, '删除成功!')
        })
      }).catch(() => {
        return false
      })
    },
    handleCreate(row) {
      this.dataForm.parentId = row.id
      this.dataForm.parentName = row.name
      this.isAdd = true
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    save() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          CategoryService.addCategory(this.dataForm).then(() => {
            this.initList()
            this.destroyDialog()
            Notify.success(this, '新增成功!')
          })
        }
      })
    },
    handleUpdate(row) {
      this.isAdd = false
      this.dialogFormVisible = true
      this.dataForm = Object.assign({}, row)
      if (this.dataForm.pic) {
        this.fileList.push({ url: this.dataForm.url })
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    edit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          CategoryService.editCategory(this.dataForm).then(() => {
            this.initList()
            this.destroyDialog()
            Notify.success(this, '更新成功!')
          })
        }
      })
    },
    destroyDialog() {
      this.dialogFormVisible = false
      this.fileList = []
      this.resetForm()
    },
    uploadCoverSuccess(data) {
      this.dataForm.pic = data.path
    },
    removeCoverSuccess() {
      this.dataForm.pic = undefined
    }
  }
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;
  }
</style>
